

import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;



public class GalleriaMaker  extends JPanel implements ActionListener {


	private static final long serialVersionUID = 1L;

	static final String PLACEHOLDER = "<!--DYNAMIC_CONTENT-->";

	private static final String SUBDIR_THUMBNAIL = "thumb";
	private static final String SUBDIR_ORIGINALS = "original";
	private static final int HEIGHT_THUMBNAILS = 64;
	private static final int HEIGHT_RESIZED = 1000;

	JButton go;

	JFileChooser chooser;
	String choosertitle;

	public GalleriaMaker() {
		go = new JButton("Choose Directory");
		go.addActionListener(this);
		add(go);
	}

	public void actionPerformed(ActionEvent e) {
		chooser = new JFileChooser(); 
		chooser.setCurrentDirectory(new java.io.File("."));
		chooser.setDialogTitle(choosertitle);
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		//
		// disable the "All files" option.
		//
		chooser.setAcceptAllFileFilterUsed(false);
		//    
		if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
			System.out.println("getCurrentDirectory(): " 
					+  chooser.getCurrentDirectory());
			System.out.println("getSelectedFile() : " 
					+  chooser.getSelectedFile());

			resizeOriginals(chooser.getSelectedFile());
			generateThumbnails(chooser.getSelectedFile());
			String html = generateHtml(chooser.getSelectedFile());
			String filecontent = fillTemplate(html);
			String dstPath = chooser.getSelectedFile().getAbsolutePath(); 
			writeFile(dstPath, "index.html", filecontent);
			copyLibraries(dstPath);
			File dstFile = new File(dstPath+"\\index.html");

			try {

				URI uri = dstFile.toURI();
				java.awt.Desktop.getDesktop().browse(uri);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 


		}
		else {
			System.out.println("No Selection ");

		}
	}

	private void resizeOriginals(File folder) {
		System.out.println("Resizing images.");
		makeDirectory(folder.getAbsolutePath()+"/"+SUBDIR_ORIGINALS+"/");
		File[] listOfFiles = folder.listFiles(); 
		for (int i = 0; i < listOfFiles.length; i++) 
		{
			if (listOfFiles[i].isFile()) 
			{
				String file = listOfFiles[i].getName();
				String[] split = file.split("\\.");
				if((split==null)||(split.length<=1)){
					System.out.println("Ignoring file "+file+". ");
				} else {
					String extension = split[split.length-1];
					if((extension.equalsIgnoreCase("png"))||(extension.equalsIgnoreCase("jpg"))){
						System.out.println("Processing file "+file+". ");
						try {
							BufferedImage image=(BufferedImage)ImageIO.read(listOfFiles[i]);
							if(image.getHeight()>HEIGHT_RESIZED){
								float ratio = (float)HEIGHT_RESIZED/(float)image.getHeight();
								int newwidth = (int)((float)image.getWidth()*ratio); 
								BufferedImage thumb=createResizedCopy(image, newwidth, HEIGHT_RESIZED, true);
								if(thumb==null){
									System.out.println("Resizing failed.");

								} else {
									System.out.println("Image successfully resized.");
									if(copy(folder.getAbsolutePath()+"/"+listOfFiles[i].getName(), folder.getAbsolutePath()+"/"+SUBDIR_ORIGINALS+"/"+listOfFiles[i].getName())){
										saveImage(thumb, folder.getAbsolutePath()+"/"+listOfFiles[i].getName());
									} else {
										System.out.println("Unable to move original file. NOT overriding it with resized file "+file+". ");
									}
								}

							} else {
								System.out.println("Image already small. No resized version created for "+file+". ");
							}
						} catch (IOException e) {

							System.out.println("Failed to create resized version of file "+file+". ");
							e.printStackTrace();
						}
					} else {
						System.out.println("Ignoring file "+file+". ");
					}
				}





			}
		}
	}


	private void generateThumbnails(File folder) {
		System.out.println("Creating thumbnails.");
		makeDirectory(folder.getAbsolutePath()+"/"+SUBDIR_THUMBNAIL+"/");
		File[] listOfFiles = folder.listFiles(); 
		for (int i = 0; i < listOfFiles.length; i++) 
		{
			if (listOfFiles[i].isFile()) 
			{
				String file = listOfFiles[i].getName();
				String[] split = file.split("\\.");
				if((split==null)||(split.length<=1)){
					System.out.println("Ignoring file "+file+". ");
				} else {
					String extension = split[split.length-1];
					if((extension.equalsIgnoreCase("png"))||(extension.equalsIgnoreCase("jpg"))){
						System.out.println("Processing file "+file+". ");
						try {
							BufferedImage image=(BufferedImage)ImageIO.read(listOfFiles[i]);
							if(image.getHeight()>HEIGHT_THUMBNAILS){
								float ratio = (float)HEIGHT_THUMBNAILS/(float)image.getHeight();
								int newwidth = (int)((float)image.getWidth()*ratio); 
								BufferedImage thumb=createResizedCopy(image, newwidth, HEIGHT_THUMBNAILS, true);
								if(thumb==null){
									System.out.println("Resizing failed.");

								} else {
									System.out.println("Image successfully resized.");
									saveImage(thumb, folder.getAbsolutePath()+"/"+SUBDIR_THUMBNAIL+"/"+listOfFiles[i].getName());
								}

							} else {
								System.out.println("Image already small. No thumbnail created for "+file+". ");
							}
						} catch (IOException e) {

							System.out.println("Failed to create thumbnail for file "+file+". ");
							e.printStackTrace();
						}
					} else {
						System.out.println("Ignoring file "+file+". ");
					}
				}





			}
		}
	}

	private void saveImage(BufferedImage image, String filename) {
		File file = new File(filename);

		try {
			System.out.println("Writing file "+filename+". ");
			ImageIO.write(image, "jpg", file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Failed.");
			e.printStackTrace();
		}
	}

	BufferedImage createResizedCopy(Image originalImage, 
			int scaledWidth, int scaledHeight, 
			boolean preserveAlpha)
	{

		int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
		BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
		Graphics2D g = scaledBI.createGraphics();
		if (preserveAlpha) {
			g.setComposite(AlphaComposite.Src);
		}
		g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
		g.dispose();
		return scaledBI;
	}

	private boolean makeDirectory(String dir){
		boolean success = (new File(dir)).mkdir();
		return success;
	}

	private void copyLibraries(String absolutePath) {
		URL url01 = GalleriaMaker.class.getResource("./res/galleria/galleria.js");
		URL url02 = GalleriaMaker.class.getResource("./res/galleria/jquery-1.4.2.js");
		URL url03 = GalleriaMaker.class.getResource("./res/galleria/plugins/galleria.flickr.js");
		URL url04 = GalleriaMaker.class.getResource("./res/galleria/plugins/galleria.history.js");
		URL url05 = GalleriaMaker.class.getResource("./res/galleria/plugins/galleria.ssp.js");
		URL url06 = GalleriaMaker.class.getResource("./res/galleria/themes/classic/galleria.classic.js");
		URL url07 = GalleriaMaker.class.getResource("./res/galleria/themes/classic/galleria.classic.css");
		URL url08 = GalleriaMaker.class.getResource("./res/galleria/themes/classic/classic-loader.gif");
		URL url09 = GalleriaMaker.class.getResource("./res/galleria/themes/classic/classic-map.png");

		makeDirectory(absolutePath+"/lib/");
		makeDirectory(absolutePath+"/lib/plugins/");
		makeDirectory(absolutePath+"/lib/themes/");
		makeDirectory(absolutePath+"/lib/themes/classic");

		if(!copy(url01.getFile(), absolutePath+"/lib/galleria.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url02.getFile(), absolutePath+"/lib/jquery-1.4.2.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url03.getFile(), absolutePath+"/lib/plugins/galleria.flickr.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url04.getFile(), absolutePath+"/lib/plugins/galleria.history.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url05.getFile(), absolutePath+"/lib/plugins/galleria.ssp.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url06.getFile(), absolutePath+"/lib/themes/classic/galleria.classic.js")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url07.getFile(), absolutePath+"/lib/themes/classic/galleria.classic.css")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url08.getFile(), absolutePath+"/lib/themes/classic/classic-loader.gif")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}
		if(!copy(url09.getFile(), absolutePath+"/lib/themes/classic/classic-map.png")){
			System.out.println("Cannot write output file! Make sure the selected directory is writeable!!!");
		}








	}

	private void writeFile(String path, String file, String filecontent) {
		try {
			FileWriter outFile = new FileWriter(path + "/" + file);
			PrintWriter out = new PrintWriter(outFile);

			// Also could be written as follows on one line
			// Printwriter out = new PrintWriter(new FileWriter(args[0]));

			// Write text to file
			out.print(filecontent);

			out.close();
		} catch (IOException e){
			e.printStackTrace();
		}

	}

	// Copies src file to dst file.
	boolean copy(String srcname, String dstname) {
		try {
			File src = new File(srcname);
			File dst = new File(dstname);
			InputStream in = new FileInputStream(src);
			OutputStream out = new FileOutputStream(dst);

			// Transfer bytes from in to out
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return true;

	}

	private String fillTemplate(String html) {
		URL url = GalleriaMaker.class.getResource("./template.html");

		File file=null;
		try {
			file = new File(url.toURI());
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		StringBuffer contents = new StringBuffer();
		BufferedReader reader = null;

		try
		{
			reader = new BufferedReader(new FileReader(file));
			String text = null;

			// repeat until all lines is read
			while ((text = reader.readLine()) != null)
			{
				contents.append(text)
				.append(System.getProperty(
				"line.separator"));
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (reader != null)
				{
					reader.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		String content = contents.toString();
		//System.out.println(content);

		content = content.replace(PLACEHOLDER, html);
		return content;

	}

	private String generateHtml(File folder) {
		File[] listOfFiles = folder.listFiles(); 
		String htmloutput = ""; 
		for (int i = 0; i < listOfFiles.length; i++) 
		{
			if (listOfFiles[i].isFile()) 
			{
				String[] split = listOfFiles[i].getName().split("\\.");
				if((split==null)||(split.length<=1)){
					System.out.println("Ignoring file "+listOfFiles[i].getName()+".");
				} else {

					String extension = split[split.length-1];
					if((extension.equalsIgnoreCase("png"))||(extension.equalsIgnoreCase("jpg"))){


						String file = listOfFiles[i].getName();
						String thumb = "./"+SUBDIR_THUMBNAIL+"/"+listOfFiles[i].getName();
						String html = "<div> <a href=\""+file+"\">";
						html += "<img src=\""+thumb+"\">";
						html += "</a> </div>";
						htmloutput += html+"\n";
					} 
				}
			}
		}

		return htmloutput;
	}


	public Dimension getPreferredSize(){
		return new Dimension(200, 200);
	}

	public static void main(String s[]) {


		JFrame frame = new JFrame("");
		GalleriaMaker panel = new GalleriaMaker();
		frame.addWindowListener(
				new WindowAdapter() {
					public void windowClosing(WindowEvent e) {
						System.exit(0);
					}
				}
		);
		frame.getContentPane().add(panel,"Center");
		frame.setSize(panel.getPreferredSize());
		frame.setVisible(true);
	}
}

